#!/bin/bash

# Script used to add/remove setup of private bridge and dnsmasq
# @author Amos Kong 

brname='br0'

add_br()
{
    echo "add new private bridge"
    /sbin/brctl addbr $brname
    echo 1 > /proc/sys/net/ipv6/conf/$brname/disable_ipv6
    echo 1 > /proc/sys/net/ipv4/ip_forward
    /sbin/brctl setfd $brname 0
    /sbin/brctl stp $brname on
    #/sbin/brctl setfd $brname 0
    /sbin/ifconfig $brname 172.16.1.1
    /sbin/ifconfig $brname up
    # add iptable entry as libvirt, then guest can access public network
    /sbin/iptables -t nat -A POSTROUTING -s 172.16.1.254/24 ! -d 172.16.1.254/24 -j MASQUERADE
   /etc/init.d/dnsmasq stop
    /etc/init.d/tftpd-hpa stop 2>/dev/null
    /usr/sbin/dnsmasq --strict-order --bind-interfaces --listen-address 172.16.1.1 --dhcp-range 172.16.1.2,172.16.1.254 $tftp_cmd
}

del_br()
{
    echo "cleanup bridge setup"
    kill -9 `pgrep dnsmasq|tail -1`
    /sbin/ifconfig $brname down
    /sbin/brctl delbr $brname
   /sbin/iptables -t nat -D POSTROUTING -s 172.16.1.254/24 ! -d 172.16.1.254/24 -j MASQUERADE
}

# clean original setup first
del_br 2>/dev/null

if [[ $# > 0 ]];then
    if [[ $# = 2 ]];then
        # setup tftp function
       tftp_cmd=" --enable-tftp --tftp-root $1 --dhcp-boot $2 --dhcp-no-override"
    fi
    add_br
fi
